package com.csu.bailan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.csu.bailan.common.CommonResponse;
import com.csu.bailan.common.ResponseEnum;
import com.csu.bailan.domain.Address;
import com.csu.bailan.domain.Signon;
import com.csu.bailan.domain.User;
import com.csu.bailan.dto.AddrDTO;
import com.csu.bailan.persistence.mapper.AddressMapper;
import com.csu.bailan.persistence.mapper.SignonMapper;
import com.csu.bailan.persistence.mapper.UserMapper;
import com.csu.bailan.service.UserService;
import com.csu.bailan.util.MD5Util;
import com.csu.bailan.dto.UpdateUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SignonMapper signonMapper;
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public CommonResponse<User> getUserByUNandPW(String username, String password) throws Exception {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user != null) {
            Signon signon = signonMapper.selectOne(new QueryWrapper<Signon>().eq("user_id", user.getUserId()));
            System.out.println(signon.toString());
            boolean check = MD5Util.validPassword(password, signon.getPassword(), signon.getSalt());
            if (check){
                log.info("查询成功且密码校验正确");
                return CommonResponse.createForSuccess(user);
            }
            else {
                log.error("用户名或密码错误");
                return CommonResponse.createForError(ResponseEnum.NameorPasswordERROR.getCode(),ResponseEnum.NameorPasswordERROR.getMessage());
            }
        }
        else {
            return CommonResponse.createForError(ResponseEnum.NameisNullERROR.getCode(),ResponseEnum.NameisNullERROR.getMessage());
        }
    }

    @Override
    public User getUserByNickname(String nickname) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("nickname", nickname);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public CommonResponse<User> createUser(User user, Signon signon){
        int num1 = userMapper.insert(user);
        if (num1>0){
            signon.setUserId(user.getUserId());
        }
        else return CommonResponse.createForError(ResponseEnum.CreateUserERROR.getCode(), ResponseEnum.CreateUserERROR.getMessage());
        int num2 = signonMapper.insert(signon);

        if (num2 > 0){
            log.info("成功插入用户表与密码表");
            return CommonResponse.createForSuccess(user);
        }
        return CommonResponse.createForError(ResponseEnum.CreateUserERROR.getCode(), ResponseEnum.CreateUserERROR.getMessage());
    }

    @Override
    public CommonResponse<User> deleteUserByUserid(String userId) {
        int utd = userMapper.delete(new QueryWrapper<User>().eq("user_id", userId));
        int sotd = signonMapper.delete(new QueryWrapper<Signon>().eq("user_id", userId));
        if (utd > 0 && sotd >0){
            log.info("删除用户表及密码表成功");
            return CommonResponse.createForSuccess();
        }
        else {
            log.error("删除用户表及密码表失败");
            return CommonResponse.createForError(ResponseEnum.DeleteUserERROR.getCode(), ResponseEnum.DeleteUserERROR.getMessage());
        }
    }

    @Override
    public CommonResponse<User> deleteUserByUsername(String username) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        String userId = user.getUserId();
        int utd = userMapper.deleteById(user);
        int sotd = signonMapper.delete(new QueryWrapper<Signon>().eq("user_id", userId));
        if (utd > 0 && sotd >0){
            log.info("删除用户表及密码表成功");
            return CommonResponse.createForSuccess();
        }
        else {
            log.error("删除用户表及密码表失败");
            return CommonResponse.createForError(ResponseEnum.DeleteUserERROR.getCode(), ResponseEnum.DeleteUserERROR.getMessage());
        }
    }

    @Override
    public CommonResponse<User> updateUserInfo(UpdateUserDTO updateUserDTO) {
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getUsername, updateUserDTO.getUsername())
                .set(User::getEmail, updateUserDTO.getEmail())
                .set(User::getNickname, updateUserDTO.getNickname())
                .set(User::getPhone, updateUserDTO.getPhone())
                .set(User::getBirthday, updateUserDTO.getBirthday())
                .set(User::getUpdateTime, new Date());
        int u = userMapper.update(null, lambdaUpdateWrapper);
        if (u > 0 ){
            log.info("更新用户信息成功");
            return CommonResponse.createForSuccess();
        }
        else {
            log.error("更新用户信息失败");
            return CommonResponse.createForError(ResponseEnum.UpdateUserERROR.getCode(), ResponseEnum.UpdateUserERROR.getMessage());
        }
    }

    @Override
    public CommonResponse<List<Address>> getAddrByUserid(String userId) {
        return CommonResponse.createForSuccess(addressMapper.selectList(new QueryWrapper<Address>().eq("user_id", userId)));
    }

    @Override
    public CommonResponse<User> updatePassword(String username, String newpasswd1, String newpassword2) throws Exception {
        if(newpasswd1.equals(newpassword2)){
            String userId = userMapper.selectOne(new QueryWrapper<User>().eq("username", username)).getUserId();
            Signon signon = new Signon();
            Map<String, String> map = MD5Util.getEncryptedPwd(newpasswd1);
            signon.setUpdateTime(new Date());
            signon.setUserId(userId);
            signon.setPassword(map.get("ep"));
            signon.setSalt(map.get("salt"));
            int sm = signonMapper.updateById(signon);
            if (sm>0){
                log.info("密码更新成功");
                return CommonResponse.createForSuccess();
            }
            else {
                log.error("密码更新失败");
                return CommonResponse.createForError(ResponseEnum.UpdatePasswrodERROR.getCode(), ResponseEnum.UpdatePasswrodERROR.getMessage());
            }
        }
        else return CommonResponse.createForError(ResponseEnum.PassWordInconsistentERROR.getCode(), ResponseEnum.PassWordInconsistentERROR.getMessage());

    }

    @Override
    public CommonResponse<User> updatePassword(User user, String newpasswd1, String newpasswd2) throws Exception {
        if(newpasswd1.equals(newpasswd2)){
            Signon signon = signonMapper.selectOne(new QueryWrapper<Signon>().eq("user_id", user.getUserId()));
            Map<String, String> map = MD5Util.getEncryptedPwd(newpasswd1);
            signon.setPassword(map.get("ep"));
            signon.setSalt(map.get("salt"));
            int up = signonMapper.updateById(signon);
            if (up>0){
                log.info("密码更新成功");
                return CommonResponse.createForSuccess();
            }
            else {
                log.error("密码更新失败");
                return CommonResponse.createForError(ResponseEnum.UpdatePasswrodERROR.getCode(), ResponseEnum.UpdatePasswrodERROR.getMessage());
            }
        }
        else return CommonResponse.createForError(ResponseEnum.PassWordInconsistentERROR.getCode(), ResponseEnum.PassWordInconsistentERROR.getMessage());
    }

    @Override
    public CommonResponse<Address> updateAddr(AddrDTO addrDTO) {
        Address address = addressMapper.selectById(addrDTO.getAddrId());
        if (address == null)
            return CommonResponse.createForError(ResponseEnum.AddressUpdateERROR.getCode(), ResponseEnum.AddressUpdateERROR.getMessage());
        address.setPhone(addrDTO.getPhone());
        address.setArea(addrDTO.getArea());
        address.setCity(addrDTO.getCity());
        address.setStreet(addrDTO.getStreet());
        address.setProvince(addrDTO.getProvince());
        address.setName(addrDTO.getName());
        int flag = addressMapper.updateById(address);
        if (flag >= 1)
            return CommonResponse.createForSuccess(address);
        return CommonResponse.createForError(ResponseEnum.AddressUpdateERROR.getCode(), ResponseEnum.AddressUpdateERROR.getMessage());
    }

    @Override
    public CommonResponse<Address> newAddr(AddrDTO addrDTO) {
        User user = userMapper.selectById(addrDTO.getUserId());
        if (user == null)
            return CommonResponse.createForError(ResponseEnum.AddressCreateERROR.getCode(), ResponseEnum.AddressCreateERROR.getMessage());
        Address address = new Address();
        address.setUserId(addrDTO.getUserId());
        address.setPhone(addrDTO.getPhone());
        address.setArea(addrDTO.getArea());
        address.setCity(addrDTO.getCity());
        address.setStreet(addrDTO.getStreet());
        address.setProvince(addrDTO.getProvince());
        address.setName(addrDTO.getName());
        int flag = addressMapper.insert(address);
        if (flag >= 1)
            return CommonResponse.createForSuccess(address);
        return CommonResponse.createForError(ResponseEnum.AddressCreateERROR.getCode(), ResponseEnum.AddressCreateERROR.getMessage());
    }
}
